
package fctuc.dei.myTwitter.com;

import java.nio.channels.SelectionKey;
import java.util.LinkedList;

public abstract class Connection {
	public LinkedList<Message> sentMsgs = new LinkedList<Message>();
	private MessageHandler mh;
	private boolean serverUp;

	public Connection(MessageHandler handler) {
		mh = handler;
	}

	public abstract boolean realSend(Message m);
	public abstract boolean realSend(Message m, SelectionKey key);
	public abstract void realTerminate();
	public abstract void noConnectionWarning();

	public void terminate() {
		realTerminate();
	}

	public boolean send(MT type, Object... args) {
		return send(new Message(type, args));
	}

	public boolean send(Message m) {
		if (!serverUp) {
			if(m.type == MT.TWEET){
				synchronized (sentMsgs) {
					sentMsgs.add(m);
				}
			}
		}

		return realSend(m);
	}


	synchronized public boolean receive(Message m) {
		mh.handleMessage(m, this);
		return true;
	}
	
	synchronized public boolean receive(Message m, SelectionKey sk){
		mh.handleNioMessage(m, sk);
		return true;
	}

	public void repeatAll() {
		int size = sentMsgs.size();
		for (int i = 0; i<size; i++){
			System.out.println("A reenviar");
			send(sentMsgs.remove());
		}
	}

	public boolean getServerStatus(){
		return this.serverUp;
	}

	public void setServerStatus(boolean status){
		this.serverUp = status;
	}
}
